package com.project.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * websocket服务类
 */
@ServerEndpoint("/socketInfo")
@Component
public class WebSocketServer {
    private static List<Session> sessionList = new ArrayList<>();
    //客户端和服务器建立连接时触发
    @OnOpen
    public void onOpen(Session s){
        System.out.println("websocket连接建立");
        sessionList.add(s);
    }

    //客户端和服务器断开连接时触发
    @OnClose
    public void onClose(Session s){
        sessionList.remove(s);
        System.out.println("websocket连接关闭");
    }
    //客户端向服务器发送消息时触发
    @OnMessage
    public void onMessage(String msg,Session s) throws IOException {
        //向每个建立websocket连接客户端推送消息
        for(Session session : sessionList){
            session.getBasicRemote().sendText(msg);
        }
    }

    //websocket发生异常时触发
    @OnError
    public void onError(Throwable e){

    }
}
